<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Support\Facades\Cache;

class CheckLogin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        try {
            $user = decrypt($request->token);
        } catch (DecryptException $e) {
            return response()->json(['error' => '非法参数，请重新登录尝试', 'success' => false]);
        }
        if (!Cache::has($user->username)) {
            return response()->json(['error' => '登录过期，请重新登录', 'success' => false]);
        }
        $request->userinfo = $user;
        return $next($request);
    }
}
